package com.example.demo_text;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import user.User;

import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/PublishExamServlet")
public class PublishExamServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        try {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null || user.getUserType().equals("student")) {
                response.sendRedirect("index.jsp");
                return;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp?message=" + e.getMessage());
            return;
        }
        try {
            // Get parameters from the request
            String courseIdStr = request.getParameter("course_id");
            String examTitle = request.getParameter("exam_title");
            String examDateStr = request.getParameter("exam_date");
            String examTimeStr = request.getParameter("exam_time");
            String examDurationStr = request.getParameter("exam_duration");
            String examDescription = request.getParameter("exam_description");
            
            // Convert parameters to appropriate types
            int courseId = Integer.parseInt(courseIdStr);
            int examDuration = Integer.parseInt(examDurationStr);
            
            // Convert string dates and times to SQL types
            Date examDate = Date.valueOf(examDateStr);
            Time examTime = Time.valueOf(examTimeStr + ":00");  // Add seconds
            
            // By default, set exams as active
            boolean active = true;
            
            // Add exam to database
            boolean success = ExamDAO.addExam(courseId, examTitle, examDate, examTime, 
                                           examDuration, examDescription, active);
            
            if (success) {
                // Redirect back to class_space.jsp with the exams tab active
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=exams");
            } else {
                // If there was an error, redirect with an error parameter
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=exams&error=Failed to create exam");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            // If an error occurred, redirect to an error page
            response.sendRedirect("error.jsp?message=" + e.getMessage());
        }
    }
} 